package com.rent.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rent.common.constant.CommonConstant;
import com.rent.common.entity.PageInfo;
import com.rent.common.exception.BusinessException;
import com.rent.common.interceptor.UserContext;
import com.rent.common.util.RedisUtil;
import com.rent.message.constant.MessageConstant;
import com.rent.message.pojo.dto.ChatMessageQueryDto;
import com.rent.message.pojo.dto.SendMessageDto;
import com.rent.message.pojo.entity.ChatMessage;
import com.rent.message.mapper.ChatMessageMapper;
import com.rent.message.pojo.vo.LastMessageVo;
import com.rent.message.pojo.vo.MessageVo;
import com.rent.message.pojo.vo.MessagesListVo;
import com.rent.message.service.ChatMessageService;
import com.rent.message.service.ConversationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {


    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private ConversationService conversationService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public Page<MessagesListVo> getMessagesListByUserId(PageInfo pageInfo) {
        Long userId = UserContext.getUserId();
        log.info("获取用户{}的消息列表",userId);
        Page<MessagesListVo> page = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        page = chatMessageMapper.getMessagesListByUserId(page, userId);
        return page;
    }

    @Override
    public List<MessageVo> getMessages(ChatMessageQueryDto dto) {
        Long myUserId = UserContext.getUserId();
        clearUnreadMessages(myUserId);
        return chatMessageMapper.getMessages(dto, myUserId);

    }

    @Override
    public void batchSave(List<ChatMessage> messages) {
//        //如果接收者聊天对象是发送用户，则将消息设置为已读
//        List<ChatMessage> processedMessages = messages.stream()
//                .peek(message -> {
//                    Object fromUserObj = redisTemplate.opsForValue().get(MessageConstant.CHAT_USER_ID + message.getGetUserId());
//                    Long fromUser = null;
//                    if (fromUserObj instanceof Integer) {
//                        fromUser = ((Integer) fromUserObj).longValue();
//                    } else if (fromUserObj instanceof Long) {
//                        fromUser = (Long) fromUserObj;
//                    }
//
//                    if(fromUser != null && fromUser.equals(message.getPostUserId())){
//                        message.setIsRead(1);
//                    }else{
////                        Long unreadCount = Long.valueOf(conversationService.getUnreadCount(message.getPostUserId(), message.getGetUserId()));
//                        conversationService.setUnreadCount(message.getGetUserId(),message.getPostUserId());
//
//                    }
//                    conversationService.setLastMessage(message);
//
//                })
//                .collect(Collectors.toList());
//
//
//
//        this.saveBatch(processedMessages);




        // 用于存储所有待更新的会话信息
        Map<String, Integer> unreadCounts = new HashMap<>();

        // 处理每条消息
        List<ChatMessage> processedMessages = messages.stream()
                .peek(message -> {
                    Object fromUserObj = redisTemplate.opsForValue().get(MessageConstant.CHAT_USER_ID + message.getGetUserId());
                    Long fromUser = null;
                    if (fromUserObj instanceof Integer) {
                        fromUser = ((Integer) fromUserObj).longValue();
                    } else if (fromUserObj instanceof Long) {
                        fromUser = (Long) fromUserObj;
                    }

                    // 如果接收者是发送者本人，设为已读
                    if (fromUser != null && fromUser.equals(message.getPostUserId())) {
                        message.setIsRead(1);
                    } else {
                        // 记录未读消息数量更新操作
                        String key = message.getGetUserId() + "_" + message.getPostUserId();
                        unreadCounts.put(key, unreadCounts.getOrDefault(key, 0) + 1);
                    }

                    // 设置最后一条消息
                    conversationService.setLastMessage(message);
                })
                .collect(Collectors.toList());

        // 批量更新未读消息数
        conversationService.updateUnreadCountBatch(unreadCounts);

        // 保存消息
        this.saveBatch(processedMessages);
    }

    @Override
    public List<MessageVo> setChatUser(Long userId) {
        Long myUserId = UserContext.getUserId();
        //设置聊天对象的id
        redisTemplate.opsForValue().set(MessageConstant.CHAT_USER_ID + myUserId, userId);
        //尝试获取一些用户的未读信息
        List<MessageVo> messages = chatMessageMapper.getUnreadMessages(myUserId, userId);

        LambdaQueryWrapper<ChatMessage> wrapper = Wrappers.lambdaQuery(ChatMessage.class);
        wrapper.eq(ChatMessage::getGetUserId, myUserId)
                .or().eq(ChatMessage::getPostUserId, userId)
                .eq(ChatMessage::getIsRead, 0);
        List<ChatMessage> list = list(wrapper);
        for (ChatMessage message : list) {
            message.setIsRead(1);
            updateById(message);
        }
        // 清理未读消息
        this.clearUnreadMessages(userId);

        return messages;
    }

    @Override
    public void clearChatUser() {
        Long myUserId = UserContext.getUserId();
        //设置聊天对象的id
        redisTemplate.opsForValue().set(MessageConstant.CHAT_USER_ID + myUserId, 0L);
    }

    private void clearUnreadMessages(Long userId) {
        LambdaQueryWrapper<ChatMessage> wrapper = Wrappers.lambdaQuery(ChatMessage.class);
        wrapper.eq(ChatMessage::getGetUserId, userId)
                .eq(ChatMessage::getIsRead, 0);
        conversationService.unreadClear(userId);
    }


}
